package com.peng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.peng.exception.YyghException;
import com.peng.helper.JwtHelper;
import com.peng.result.ResultCodeEnum;
import com.peng.service.PatientService;
import com.peng.service.UserInfoService;
import com.peng.mapper.UserInfoMapper;
import com.peng.yygh.enums.AuthStatusEnum;
import com.peng.yygh.model.user.Patient;
import com.peng.yygh.model.user.UserInfo;
import com.peng.yygh.vo.user.LoginVo;
import com.peng.yygh.vo.user.UserAuthVo;
import com.peng.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author dell
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-06-07 14:03:27
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //TODO 校验校验验证码
        String s = redisTemplate.opsForValue().get(phone);
        if (!s.equals(code)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //绑定手机号码
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.getByOpenid(loginVo.getOpenid());
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }
        if (userInfo==null){
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getPhone,phone);
            userInfo = this.getOne(queryWrapper);
            if(null == userInfo) {
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                this.save(userInfo);
            }
        }

        //校验是否被禁用
        if(userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //TODO 记录登录

        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }

    @Override
    public UserInfo getByOpenid(String openid) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getOpenid,openid);
        UserInfo one = this.getOne(queryWrapper);
        return one;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo byId = this.getById(userId);
        if (byId!=null){
            byId.setName(userAuthVo.getName());
            byId.setCertificatesNo(userAuthVo.getCertificatesNo());
            byId.setCertificatesType(userAuthVo.getCertificatesType());
            byId.setCertificatesUrl(userAuthVo.getCertificatesUrl());
            byId.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        }
        this.updateById(byId);
    }

    @Override
    public Page<UserInfo> selectPage(Page<UserInfo> page1, UserInfoQueryVo userInfoQueryVo) {
        String keyword = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(keyword!=null, UserInfo::getName,keyword);
        queryWrapper.eq(authStatus!=null,UserInfo::getAuthStatus,authStatus);
        queryWrapper.eq(status!=null,UserInfo::getStatus,status);
        queryWrapper.gt(createTimeBegin!=null, UserInfo::getCreateTime,createTimeBegin);
        queryWrapper.lt(createTimeEnd!=null, UserInfo::getUpdateTime,createTimeEnd);
        Page<UserInfo> page = this.page(page1, queryWrapper);
        page.getRecords().stream().forEach(item->{
            this.packageUserInfo(item);
        });
        return page;
    }

    @Override
    public Map<String, Object> show(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        UserInfo userInfo = this.getById(userId);
        UserInfo userpack = this.packageUserInfo(userInfo);
        map.put("userInfo",userpack);
        List<Patient> allUserId = patientService.findAllUserId(userId);
        map.put("patientList",allUserId);
        return map;
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }

}




